﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;

namespace JLT.Countdown.Models
{
    public class BusArrival
    {
 
        public arrivalsWrapper Root;
        private arrivalsWrapper wrapper;

        public void getData(int stopId)
        {
            //Go out to the web and get arrivals in JSON Format
            //e.g. http://countdown.tfl.gov.uk/stopBoard/50100

            string url = "http://countdown.tfl.gov.uk/stopBoard/" + stopId;

            // used to build entire input
            StringBuilder sb = new StringBuilder();

            // used on each read operation
            byte[] buf = new byte[8192];

            // prepare the web page we will be asking for
            HttpWebRequest request = (HttpWebRequest)
                WebRequest.Create(url);

            try
            {

                // execute the request
                HttpWebResponse response = (HttpWebResponse)
                    request.GetResponse();

                // we will read data via the response stream
                Stream resStream = response.GetResponseStream();

                string tempString = null;
                int count = 0;

                do
                {
                    // fill the buffer with data
                    count = resStream.Read(buf, 0, buf.Length);

                    // make sure we read some data
                    if (count != 0)
                    {
                        // translate from bytes to ASCII text
                        tempString = Encoding.ASCII.GetString(buf, 0, count);

                        // continue building the string
                        sb.Append(tempString);
                    }
                }
                while (count > 0); // any more data to read?

                string s = sb.ToString();

                JavaScriptSerializer serializer = new JavaScriptSerializer();

                wrapper = serializer.Deserialize<arrivalsWrapper>(s);
                wrapper.error = "";

            }

            catch (Exception ex)
            {
                wrapper = new arrivalsWrapper();
                wrapper.error = ex.Message;
            }

            this.Root = wrapper;
        }
    }
}
